package com.example.demo_homework2.controller;

import com.example.demo_homework2.bean.CmsCategory;
import com.example.demo_homework2.common.Response;
import com.example.demo_homework2.mapper.CmsArticleMapper;
import com.example.demo_homework2.service.CmsArtcleService;
import com.example.demo_homework2.service.CmsCategoryService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/category")
@Api(tags = "栏目信息管理")
public class CmsCategoryController {
    @Autowired
    private CmsCategoryService categoryService;

    @GetMapping("/all")
    @ApiOperation(value = "获取所有栏目信息", notes = "从数据库检索所有栏目信息返回")
    public Response<List<CmsCategory>> queryAll() {
        return Response.ok(categoryService.getAllCategory());
    }

    @ApiOperation(value = "保存或更新栏目信息", notes = "如果传参时指明了栏目编号，执行更新操作<br/>"
            + "如果传参时没有指明栏目编号，执行插入操作")
    @PostMapping("/saveOrUpdateCategory")
    public Response<String> saveOrUpdate(CmsCategory cmsCategory) {
        boolean b = categoryService.saveOrUpdate(cmsCategory);
        if (b)
            return Response.ok("操作成功");
        else return Response.error("操作失败");
    }

    @ApiOperation(value = "删除栏目信息", notes = "根据栏目编号删除栏目信息")
    @DeleteMapping("delete")
    @ApiImplicitParam(name = "id",value = "栏目编号")
    public Response<String> deleteCategory(String id) {
        int t = categoryService.deleteCategory(id);
        if (t == -1) {
            return Response.error("请先删除子栏目");
        }
        if (t == -2) {
            return Response.error("请先删除栏目中的文章");
        }
        if (t == 0) {
            return Response.error("栏目不存在");
        }
        return Response.ok("删除成功");
    }

    @DeleteMapping("deleteByIds")
    @ApiOperation(value = "删除多个栏目信息", notes = "根据栏目编号删除多个栏目信息")
    public Response<String> deleteByIds(String[] ids) {
        String s = categoryService.deleteByIds(ids);
        if (s.startsWith("success")) {
            return Response.ok(s);
        } else {
            return Response.error(s);
        }

    }
}
